package service

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"wechats/basic/config"
	"wechats/handler/model"
)

var (
	upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
	clients = map[string]*Node{}
)

type Node struct {
	userId string
	conn   *websocket.Conn
	data   chan []byte
}

func Chat(c *gin.Context) {
	userId := c.Query("userId")
	friendId := c.Query("friendId")

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	clients[userId] = &Node{
		userId: userId,
		conn:   conn,
		data:   make(chan []byte),
	}
	go RedSms(clients[userId], friendId)
	go SendS(clients[userId])
}
func RedSms(myNode *Node, friendId string) {
	var black model.BlackD
	err := black.ISBlackD(config.DB, black.UserId, black.FriendId)
	if err == nil {
		log.Println("好友已存在黑名单中")

	}
	var find model.Friend
	err = find.ISFriend(config.DB, find.UserId, find.FriendId)
	if err != nil {
		log.Println("非好友状态,请添加为好友")

	}
	for {
		_, data, err := myNode.conn.ReadMessage()
		if err != nil {
			return
		}
		var liao model.Liao
		err = liao.LiaoAdd(config.DB)
		if err != nil {
			return
		}
		userIdmyNode := clients[friendId]
		userIdmyNode.data <- data
	}
}

func SendS(myNode *Node) {
	for {
		select {
		case data := <-myNode.data:
			err := myNode.conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				return
			}
		}
	}
}
